<template>
    <div>
        <el-table
            :data="source"
            class="widget-list"
            @header-click="handleClick"
            @sort-change="handleSortChange"
            @selection-change="handleSelectChange">
            <el-table-column type="selection" width="40" v-if="check"></el-table-column>
            <el-table-column label="题图" width="270">
                <template slot-scope="{row}">
                    <div class="item img"
                        @click="fetchDetail(check ? row.appId : row._id)"
                        :style="'background-image: url(' + (row.img ? row.img : require('../../../static/images/noimg.gif')) + ')'">
                    </div>
                </template>
            </el-table-column>

            <el-table-column label="标题" prop="name" width="240">
                <template slot-scope="{row}">
                    <div class="flex flex-wrap" :class="titleAlign" :style="{height: '150px'}">
                        <div class="w-full title" @click="fetchDetail(check ? row.appId : row._id)">
                            <div class="w-full text-grey font-light ">应用编号： {{ row.code }}</div>
                            <div class="w-full text">{{ row.title }}</div>
                        </div>
                        <div v-if="popular" class="popular w-full">
                            <i class="iconfont icon-eye"></i>
                            <span>{{ row.statistics ? row.statistics.pgNum : 0 }}</span>
                            <i class="iconfont icon-star"></i>
                            <span>{{ row.statistics ? row.statistics.favNum : 0 }}</span>
                            <i class="iconfont icon-share"></i>
                            <span>{{ row.statistics ? row.statistics.shaNum : 0 }}</span>
                        </div>
                    </div>
                </template>
            </el-table-column>

            <el-table-column v-if="channel || changeType" label="收稿频道" align="center">
                <template slot-scope="{row}">
                    <template v-if="changeType">
                        <div v-for="(v, i) in row.cats" :key="i" class="text-grey font-light">{{ v.catName }}</div>
                        <!-- <div style="color: #02A7FB; cursor: pointer" @click="$refs.dialog.open(row._id, row.cats)" v-if="row.cats && row.cats.length">更改</div> -->
                    </template>

                    <template v-if="channel">
                        <div class="text-grey font-light">{{ row.channels ? row.channels.map(el => el&&el.cnname ? el.cnname :'').join('、') : '' }}</div>
                    </template>
                </template>
            </el-table-column>

            <el-table-column label="作者" prop="creatorName" align="center"  class="font-light" v-if="check">
                <template slot-scope="{row}">
                    {{ row.hide ? '匿名' : row.creatorName }}
                </template>
            </el-table-column>

            <el-table-column label="修改时间" align="center" sortable="custom" prop="updateTime" v-if="!time">
                <template slot-scope="{row}">
                    <span class="text-grey font-light">{{ row.updateTime | formatDate('yy-mm-ss hh:mm:ss') }}</span>
                </template>
            </el-table-column>
            
            <el-table-column label="提交时间" align="center" sortable="custom" prop="updateTime" v-else>
                <template slot-scope="{row}">
                    <span class="text-grey font-light">{{ row.createTime | formatDate('yy-mm-ss hh:mm:ss') }}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="140"  v-if="cancel || modify || del || past">
                <template slot-scope="{row, $index}">
                    <!-- <div><el-button type="text" style="color: #02A7FB" @click="onCancel(row.id)" v-if="cancel">撤销</el-button></div> -->
                    <div><el-button type="text" :style="row.channelApplyStatus > 2 ? 'color: #02A7FB' : 'color: #E33A4F'" v-if="cancel">{{row.channelApplyStatus > 2 ? '已收录' : '已拒绝' }}</el-button></div>
                    <div><el-button type="text" style="color: #02A7FB" @click="onApply(row.id)" v-if="modify || channel">{{$route.path.includes('finish') ? '频道投稿' : '投稿'}}</el-button></div>
                    <div><el-button type="text" style="color: #02A7FB" @click="onModify(row.id,row.type)" v-if="modify">编辑</el-button></div>
                    <div><el-button type="text" :style="$route.path.includes('finish') ? 'color: #67c23a' : 'color: #E33A4F'" @click="onDelete(row.id)" v-if="del"> {{$route.path.includes('finish') ? '转为私密' : '删除'}}</el-button></div>
                    <!-- <el-button type="text" style="color: #E33A4F" v-if="del" v-popover:popover>删除</el-button> -->

                    <template v-if="past">
                        <div><el-button type="text" style="color: #02A7FB" @click="onPast(row.appId,row.channelId)">通过</el-button></div>
                        <div><el-button type="text" style="color: #E33A4F" @click="onPast(row.appId,row.channelId, false)">不通过</el-button></div>
                    </template>
                </template>
            </el-table-column>
        </el-table>

        <!-- 改变类目 -->
        <change-category ref="dialog" v-model="update"></change-category>

        <!-- 预览 -->
        <preview :category-text="categoriesText" :labels="labels" ref="preview"></preview>
        <!-- 频道 -->
        <channel @reset="channelReset" @search="channelSearch($event)" @close="dialigClose" @typeChange="channelTypeChange" :channel-data.sync="category" @confirm='confirmChannel' :channel-selected="channelArray"  ref="channel"></channel>
    </div>
</template>

<script>
    import ChangeCategory from '../widget/ChangeCategory';
    import Preview from '../../components/widget/Preview';
    import Channel from '../../components/widget/Channel';
    import {getCategorise} from '../../config/Cache';
    import {formatCategorise} from '../../config/parameter';
    import cloneDeep from 'lodash/cloneDeep';
    import {Popover} from 'element-ui';

    export default {
        components: {
            Preview,
            ChangeCategory,
            Channel,
            ElPopover: Popover,
        },
        props: {
            // 数据
            source: {
                type: Array,
                default: () => {
                    return [];
                }
            },
            channel:{
                type: Boolean,
                default: false
            },
            popular: {
                type: Boolean,
                default: false
            },
            cancel: {
                type: Boolean,
                default: false
            },
            modify: {
                type: Boolean,
                default: false
            },
            del: {
                type: Boolean,
                default: false
            },
            check: {
                type: Boolean,
                default: false
            },
            past: {
                type: Boolean,
                default: false
            },
            time: {
                type: Boolean,
                default: false
            },
            changeType: {
                type: Boolean,
                default: false
            },
            value: null
        },
        data() {
            return {
                selected: [],
                update: false,
                types: [],
                labels: [],
                options: [],
                intervalId: {},
                category:[],
                channelArray:[],
                allCategory:[]
            };
        },
        computed: {
            titleAlign() {
                if (this.popular) return 'content-between';
                if (this.del) return '';
                return 'items-center';
            },
            categoriesText() {
                return this.types
                    .filter(el => el)
                    .map(ele => this.findName(ele));
            }
        },
        watch: {
            update(val) {
                if (!val) return;

                this.$emit('input', true);
                this.update = false;
            }
        },
        methods: {
            channelReset(val){
                console.log(val)
                this.category = val.resetList
                this.channelArray = val.resetSelected
            },
            channelSearch(val){
                console.log(val)
                API.get('application/channel/select?appId=' + val.id+'&kw='+val.kw)
                    .then(res => {
                        console.log(res.cats)
                        this.allCategory = res
                        this.category = res.cats
                        // console.log(res)
                        // let format = formatCategorise(cloneDeep(res.cats), null);
                        // console.log(format)
                    })
                    .catch(err => {
                        Ele.$message.error('操作失败！');
                    })
                    .finally(() => {
                        //this.dialogVisible = false;
                       
                    });
            },
            handleClick(value){
                console.log(value)
            },
            channelTypeChange(val){
                console.log(val)
                if(val == "其它频道"){
                    this.category = this.allCategory.others
                }else{
                    this.category = this.allCategory.cats
                }
            },
            dialigClose(){
                this.channelArray = []
            },
            confirmChannel(id){
                
                    // let data = {
                    //     appId: id,
                    //     channelIds: this.channelArray.map(el => el[el.length - 1]).join(','),
                    // };
                    
                    let _data = this.channelArray.map(item=>{
                        item.channelApplyStatus = item.channelApplyStatus == 5 ? 1 : item.channelApplyStatus
                        item.appId = id
                        item.channelId = item.id
                        return item
                    })
                    console.log(_data)
                    API.post('application/channel/batch/apply', _data)
                        .then(res => {
                            Ele.$message.success('投稿成功');
                        })
                        .catch(err => {
                            Ele.$message.error(err.status.msg);
                        })
                        .finally(() => {
                            this.$refs.channel.close()
                            this.channelArray = []
                            this.$emit('input', true);
                        });
                
                console.log(id)
                console.log(this.channelArray)
                
            },
            onApply(id){
                API.get('application/channel/select?appId=' + id)
                    .then(res => {
                        console.log(res.cats)
                        this.allCategory = res
                        this.category = res.cats
                        // console.log(res)
                        // let format = formatCategorise(cloneDeep(res.cats), null);
                        // console.log(format)
                    })
                    .catch(err => {
                        Ele.$message.error('操作失败！');
                    })
                    .finally(() => {
                        //this.dialogVisible = false;
                        this.$refs.channel.open(id)
                    });
                
            },
            clear() {
                    const len = Object.values(this.intervalId).filter(el => el);
                    if (len) {
                        const arrays = Object.entries(this.intervalId).filter(el => el[1]);
                        arrays.forEach(el => clearInterval(this.intervalId[el[0]]));
                    }
            },
            onCancel(id) {
                this.appData(id, 0);
            },
            onDelete(id) {
                const ready = this.$route.path.includes('ready');
                const text = (ready ? '本条应用将永久删除' : '公开应用转为私密时将断开所有产品与应用的关联') + '，请谨慎操作。';

                Ele.$confirm(text, '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (ready) {
                        // 草稿箱中 直接删除
                        API.delete('manage/applications/' + id).then(res => {
                            Ele.$message.success('删除成功');
                            this.$emit('input', true);
                        });
                    } else {
                        // 已审核应用删除 恢复到草稿箱
                        this.appData(id, 0);
                    }

                }).catch(() => {
                    Ele.$message('取消');
                });
            },
            onPast(id, channelId,status = true) {
                // let audit = status ? 3 : 0;
                if (!status) {
                    Ele.$prompt('确认该应用审核不通过？ 请填写审核意见', '提示', {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消审核'
                    }).then(({ value }) => {
                        console.log(value);
                        this.postData(id, channelId ,status, value);
                    }).catch(() => {
                        Ele.$message({
                            type: 'info',
                            message: '取消'
                        });
                    });
                } else {
                    this.postData(id, channelId, status);
                }
            },
            onModify(itemId,type) {
                // 'ready_modify': 修改中 - midify, 修改完成 - finish
                LocalStore.set('ready_modify_' + itemId, 'modify');
                let times = 0;
                this.intervalId[itemId] = setInterval(() => {
                    if (LocalStore.get('ready_modify_' + itemId) === 'finish') {
                        this.$emit('input', true);
                        clearInterval(this.intervalId[itemId]);
                    }
                }, 1000 * 1);
                // this.$router.push({
                //     name: 'Application.Edit',
                //     query: {
                //         id: itemId
                //     }
                // })
                if(type){
                    window.open(location.origin + '/admin/application/exedit/' + itemId, '_blank');
                }else{
                    window.open(location.origin + '/admin/application/edit/' + itemId, '_blank');
                }
                
            },
            appData(id, status, mesg = '') {
                // audit: 0.初始状态 1.审核中 2.审核未通过 3.审核通过
                let data = {
                    audit: status,
                    ids: id,
                    msg: mesg
                };

                API.post('manage/applications/audit', data).then(res => {
                    Ele.$message.success('操作成功');
                    this.$emit('input', true);
                });
            },
            postData(id, channelId , status, mesg = '') {
                // audit: 0.初始状态 1.审核中 2.审核未通过 3.审核通过
                let data = {
                    channelId: channelId,
                    appId: id,
                    msg: mesg
                };
                let _url = status ? 'application/channel/apply/aggree' : 'application/channel/apply/refuse'
                API.post(_url, data).then(res => {
                    Ele.$message.success('操作成功');
                    this.$emit('input', true);
                })
                .catch(err => {
                    Ele.$message.error('操作失败');
                })
                .finally(() => {

                });
            },
            handleSelectChange(section) {
                const ids = section.map(el => el.id || el.appId).join(',');
                this.$emit('emitSelected', ids);
            },
            handleSortChange(val) {
                console.log(val)
                let _order = val.order ? val.order : 'ascending'
                this.$emit('sortBy', _order);
            },
            // handle preview date
            fetchDetail(id) {
                this.loading = true;
                API.get('applications/' + id).then(res => {
                    this.types = res.cats.map(el => {
                        if(el&&el.catId){
                            return this.findCategoryArray(el.catId)
                        }
                    });
                    this.labels = res.labels.filter(el => el);

                    this.$refs.preview.open(res);
                }).finally(() => this.loading = false);
            },
            async fetchCategory() {
                const categories = await getCategorise('cascader');
                console.log(categories,'categories')
                //this.category = categories
                this.options = await getCategorise();
            },
            findName(array) {
                console.log(this.options.find(el => el&&el.id === array[array.length - 1]))
                if(this.options.find(el => el&&el.id === array[array.length - 1])){
                    return this.options.find(el => el&&el.id === array[array.length - 1]).text; 
                }
                
            },
            findCategoryArray(sourceId) {
                const options = this.options;
                let arr = [];
                let isFinish = true;
                let id = sourceId;

                while (isFinish) {
                    const element = options.find(el => el.id === id);
                    if (element) {
                        arr.unshift(element.id);
                        if (element.parentid) {
                            id = element.parentid;
                        } else {
                            isFinish = false;
                        }
                    } else {
                        isFinish = false;
                    }
                }
                return arr;
            },
        },
        created() {
            this.fetchCategory();
        },
    }
</script>

<style lang="scss">
    .widget-list {
        font-size: 16px;

        .item {
            width: 270px;
            height: 150px;
            margin-left: -10px;
            display: inline-block;
            vertical-align: top;

            &.img {
                background: transparent no-repeat center/cover;

                &:hover {
                    width: 270px;
                    height: 150px;
                    position: relative;
                    cursor: pointer;

                    &::after {
                        content: '预览';
                        width: 270px;
                        height: 150px;
                        color: #fff;
                        line-height: 150px;
                        text-align: center;
                        display: inline-block;
                        background-color: rgba(0, 0, 0, .1);
                    }
                }
            }
        }

        .title {
            &:hover {
                cursor: pointer;
                color: #02a4fc;
            }

            .text {
                font-size: 18px;
            }
        }
    }
</style>
